package com.jqsoft.launcher.activity;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jqsoft.launcher.activity.bean.UpdateInfo;
import com.jqsoft.launcher.common.Constant;
import com.jqsoft.launcher.login.BphsLoginActivity;
import com.jqsoft.launcher.R;
import com.jqsoft.launcher.service.UpdataService;
import com.jqsoft.launcher.util.AndroidUtil;
import com.jqsoft.launcher.util.AssetCopyUtil;
import com.jqsoft.launcher.util.DownLoadUtil;
import com.jqsoft.launcher.util.Log;
import com.jqsoft.launcher.util.UpdateInfoParser;

import org.apache.commons.lang.StringUtils;

import java.io.File;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * splash 过度页面
 * 
 * @author gujunqi date：2013-12-27
 */
public class SplashActivitys extends JQActivity {
	/** Called when the activity is first created. */
	private UpdateInfo info;
	private ProgressDialog pd;
	protected static final int COPY_SUCCESS = 30;
	protected static final int COPY_FAILED = 31;
	protected static final int COPY_COMMON_NUMBER_SUCCESS = 32;
	private static final int GET_INFO_SUCCESS = 10;
	private static final int SERVER_ERROR = 11;
	private static final int DOWNLOAD_SUCCESS = 16;
	private static final int DOWNLOAD_ERROR = 17;
	private TextView tv_splash_version;
	private RelativeLayout rl_splash;
	private ProgressBar splash_progressbar;
	private boolean copyOver = false, donghuaOver = false;
	private boolean updateOver = true;

	private Intent mIntent;
	private MsgReceiver msgReceiver;
	private SharedPreferences loginlist = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
			finish();
			return;
		}
		if (!isTaskRoot()){
			finish();
			return;
		}
	}

	@Override
	protected int getContentLayout() {
		Log.i("11", "jinruzhujiem,");
		return R.layout.splash_layout;
	}

	@Override
	protected void initGui() {
		rl_splash = (RelativeLayout) findViewById(R.id.rl_splash);
		tv_splash_version = (TextView) findViewById(R.id.tv_splash_version);
		splash_progressbar = (ProgressBar) findViewById(R.id.splash_progressbar);
		tv_splash_version.setText("版本号:" + AndroidUtil.getAPKVersion(ctx));
		// 检测版本号
		checkUpdate();
	}

	/**
	 * 检查更新
	 */
	public void checkUpdate() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					loginlist = getSharedPreferences("LOGIN_INFOS", 0);
					String Ip = loginlist.getString("ip", "");
					String port = loginlist.getString("port", "");
					if ((StringUtils.isNotBlank(Ip))
							&& (StringUtils.isNotBlank(port))) {
						// URL url = new
						// URL("http://60.171.146.122:9098/version.xml");
						URL url = new URL("http://" + Ip + ":" + port
								+ "/version.xml");
						HttpURLConnection conn = (HttpURLConnection) url
								.openConnection();
						conn.setConnectTimeout(5000);
						InputStream inStream = conn.getInputStream();
						info = UpdateInfoParser.getUpdateInfo(inStream);
						Message msg = new Message();
						msg.what = GET_INFO_SUCCESS;
						myhandler.sendMessage(msg);
					} else {
						loadDictionary();
					}
				} catch (Exception e) {
					Message msg = new Message();
					msg.what = SERVER_ERROR;
					myhandler.sendMessage(msg);
				}
			}
		}).run();
	}

	private Handler myhandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case SERVER_ERROR:
				Toast.makeText(getApplicationContext(), "连接服务器失败", Toast.LENGTH_SHORT).show();
				loadDictionary();
				break;
			case GET_INFO_SUCCESS:
				int serverversion = Integer.valueOf(info.getVersion());//服务器22
				int currentversion = getVersionCode();//客户21
				if (serverversion <= currentversion) {
					loadDictionary();
				} else {
					// Logger.i(TAG, "版本号不相同,升级对话框");
					showUpdateDialog();
				}
				break;

			case DOWNLOAD_SUCCESS:
				// Logger.i(TAG,"文件下载成功");
				File file = (File) msg.obj;
				installApk(file);
				break;
			case DOWNLOAD_ERROR:
				Toast.makeText(getApplicationContext(), "下载数据异常", Toast.LENGTH_SHORT).show();
				loadDictionary();
				break;
			}
		};
	};

	/**
	 * 安装一个apk文件 只要知道安装的路径
	 *
	 * @param file
	 */
	protected void installApk(File file) {
		/*
		 * <intent-filter> <action android:name="android.intent.action.VIEW" />
		 * <category android:name="android.intent.category.DEFAULT" /> <data
		 * android:scheme="content" /> <data android:scheme="file" /> <data
		 * android:mimeType="application/vnd.android.package-archive" />
		 * </intent-filter>
		 */
		// 1.显示意图
		// 2.隐式意图

		Intent intent = new Intent();
		intent.setAction("android.intent.action.VIEW");
		intent.addCategory("android.intent.category.DEFAULT");
		/*
		 * intent.setType("application/vnd.android.package-archive");
		 * intent.setData(Uri.fromFile(file));
		 */
		intent.setDataAndType(Uri.fromFile(file),
				"application/vnd.android.package-archive");
		startActivity(intent);
		// 泡茶 泡咖啡 泡妞 泡红茶 泡绿茶 打3瓶海天酱油
		// addCategory 额外的配置信息.
	}

	/**
	 * 显示升级提示的对话框
	 */
	protected void showUpdateDialog() {
		// 创建了对话框的构造器
		Builder builder = new Builder(this);
		builder.setIcon(getResources().getDrawable(R.drawable.logo_bg));
		builder.setTitle("升级提示");
		builder.setMessage(info.getDescription());
		pd = new ProgressDialog(SplashActivitys.this);
		pd.setMessage("正在下载");
		pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);// 指定显示进度条
		builder.setPositiveButton("升级", new OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {
				// Logger.i(TAG, "升级,下载" + info.getApkurl());
				if (Environment.MEDIA_MOUNTED.equals(Environment
						.getExternalStorageState())) {
					pd.show();
					new Thread() {

						public void run() {
							String path = info.getApkurl();
							String filename = DownLoadUtil.getFilename(path);
							File file = new File(Environment
									.getExternalStorageDirectory(), filename);
							file = DownLoadUtil.getFile(ctx, path,
									file.getAbsolutePath(), pd);
							if (file != null) {
								Message msg = Message.obtain();
								msg.what = DOWNLOAD_SUCCESS;
								msg.obj = file;
								myhandler.sendMessage(msg);
							} else {
								Message msg = Message.obtain();
								msg.what = DOWNLOAD_ERROR;
								myhandler.sendMessage(msg);
							}
							pd.dismiss();
						};
					}.start();
				} else {
					Toast.makeText(getApplicationContext(), "sd卡不可用", Toast.LENGTH_SHORT).show();
					loadDictionary();

				}
			}
		});
		builder.setNegativeButton("取消", new OnClickListener() {

			public void onClick(DialogInterface dialog, int which) {
				loadDictionary();

			}
		});
		AlertDialog dialog = builder.create();
		dialog.setCancelable(false);
		dialog.setCanceledOnTouchOutside(false);
		dialog.show();
		// builder.
		// builder.create().show();
	}

	/**
	 * 获取程序版本号
	 */
	private int getVersionCode() {
		int versionCode = 0;
		try {
			versionCode = getPackageManager().getPackageInfo(getPackageName(),
					0).versionCode;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return versionCode;
	}

	@Override
	protected void initAction() {

	}

	private void loadDictionary() {
		final File file = new File(
				"/data/data/com.jqsoft.launcher/databases/dictionary.db");
		// final File file = new File(getFilesDir(), "dictionary.db");
		// final File file =getDatabasePath("dictionary.db");
		if (file.exists() && file.length() > 0) {
			// 已经存在
			new Thread() {
				public void run() {
					if (isupdataDB()) {
						//  updataDB();
						handler.sendEmptyMessage(Constant.UPDATE_DOWNLOADING);
						updateOver = false;
					} else {
						updateOver = true;
						copyOver = true;
						Message msg = Message.obtain();
						msg.what = COPY_SUCCESS;
						handler.sendMessage(msg);
						// to(BphsLoginActivity.class);}
					}
				};
			}.start();
		} else {
			// 数据库的拷贝
			new Thread() {
				public void run() {
					AssetCopyUtil asu = new AssetCopyUtil(
							getApplicationContext());
					boolean result = asu.copyFile("dictionary.db", file);
					if (isupdataDB()) {
						// updataDB();
						handler.sendEmptyMessage(Constant.UPDATE_DOWNLOADING);
						updateOver = false;
					} else {
						if (result) {
							updateOver = true;
							copyOver = true;
							Message msg = Message.obtain();
							msg.what = COPY_SUCCESS;
							handler.sendMessage(msg);
						} else {
							Message msg = Message.obtain();
							msg.what = COPY_FAILED;
							handler.sendMessage(msg);
						}
					}
				};
			}.start();
		}
		AlphaAnimation aa = new AlphaAnimation(0.3f, 1.0f);
		aa.setDuration(1500);
		rl_splash.startAnimation(aa);
		aa.setAnimationListener(new AnimationListener() {

			public void onAnimationEnd(Animation animation) {
				donghuaOver = true;
				handler.sendEmptyMessage(Constant.MSG_LOAD_OVER);
				// to(BphsLoginActivity.class);
			}

			public void onAnimationRepeat(Animation animation) {
				// TODO Auto-generated method stub

			}

			public void onAnimationStart(Animation animation) {
				// TODO Auto-generated method stub

			}

		});

		// 动态注册广播接收器
		msgReceiver = new MsgReceiver();
		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction("com.example.communication.RECEIVER");
		registerReceiver(msgReceiver, intentFilter);
	}

	@Override
	protected void initData() {

	}

	@Override
	public void onDestroy() {
		// 停止服务
		if (null != mIntent) {
			stopService(mIntent);
		}
		// 注销广播
		if (null != msgReceiver) {
			unregisterReceiver(msgReceiver);
		}
		super.onDestroy();
	}

	/**
	 * 广播接收器
	 */
	public class MsgReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			// 拿到进度，更新UI
			int data = intent.getIntExtra("data", 0);
			if (0 == data) {
				handler.sendEmptyMessage(Constant.UPDATE_DOWNLOAD_CANCELED);
			} else {
				handler.sendEmptyMessage(data);
			}
			// mProgressBar.setProgress(progress);
		}
	}

	public boolean isupdataDB() {
		updateOver = false;
		return false;
		// String methodName = BphsURL.getCommonPath("GetDictionary_METHOD");
		// String serviceURL = BphsURL.getCommonPath("GetDictionary_URL");
		// final JSONObject updata = new JSONObject();
		// try {
		// updata.put("VersionNumber", "1.01");
		// } catch (JSONException e1) {
		// e1.printStackTrace();
		// }
		// String result= WebServiceUtils.requestByParams(methodName,
		// updata.toString(), serviceURL);
		// if(StringUtils.isNotBlank(result)){
		// JSONObject json;
		// try {
		// json = new JSONObject(result);
		// // 键3： VersionNumber 平台系统版本号
		// // 键4： IsUpdate 字典是否更新（1：更新 0：不更新）
		// String isUpdate= json.getString("IsUpdate");
		// // isUpdate= "0";
		// if("1".equals(isUpdate)){
		// return true;
		// }else{
		// return false;
		// }
		// } catch (JSONException e) {
		// }}
		// return false;
	}

	// public void updataDB(){
	// handler.sendEmptyMessage(Constant.UPDATE_DOWNLOADING);
	// updateOver=false;
	// // new Thread(){
	// // public void run() {
	// String methodName = "GetDictionaryCatalog";
	// String serviceURL =
	// "http://60.171.157.123:9098/WebService/DictionaryDetail.asmx";
	// String result= WebServiceUtils.requestNoParams(methodName, serviceURL);
	// // String result= WebServiceUtils.requestByParams(methodName,
	// logindata.toString(), serviceURL);
	// //
	// {"sSuccess":"1","sMessage":"用户登陆成功！","AllCount":0,"Data":"{\"sResult\":null,\"sMessage\":null,\"sLoginName\":\"admin\",\"sAlias\":null,\"sUserName\":\"安徽省卫生厅\",\"sOrganizationKey\":\"60bfbec0-180e-41b9-9974-007ef0d0ee43\",\"sOrgInstitutionCode\":\"X19870226\",\"sOrganizationName\":\"安徽省卫生厅\",\"sOrganizationTypeCode\":\"10\",\"sOrganizationLevelCode\":\"1\",\"sManagementDivisionCode\":\"340000\",\"sManagementDivisionName\":\"安徽省\"}"}
	// if(StringUtils.isNotBlank(result)){
	// try {
	// // DataDictionaryDao dao=new DataDictionaryDao();
	// DataDictionaryDao.deleteAll();
	// JSONArray jsonArray = new JSONArray(result);
	// for (int i = 0; i < jsonArray.length(); ++i) {
	// JSONObject o = (JSONObject) jsonArray.get(i);
	// boolean a=DataDictionaryDao.add(o.getString("gKey"),
	// o.getString("sCatalogCode"), o.getInt("iSerialNumber"),
	// o.getString("sValue"), o.getString("sCode"), 1);
	// }
	// updateOver=true;
	// handler.sendEmptyMessage(Constant.UPDATE_DOWNLOAD_CANCELED);
	// } catch (JSONException e) {
	// updateOver=true;
	// handler.sendEmptyMessage(Constant.UPDATE_DOWNLOAD_ERROR);
	// e.printStackTrace();
	// }
	// }else{
	// updateOver=true;
	// handler.sendEmptyMessage(Constant.UPDATE_DOWNLOAD_ERROR);
	// }
	//
	// // };
	// // }.start();
	//
	// }
	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case COPY_SUCCESS:
				if (copyOver && donghuaOver && updateOver) {
//					jumpToBphsLoginActivityWithoutFinishSelf();
					to(BphsLoginActivity.class);
				}
				break;
			case Constant.MSG_LOAD_OVER:
				if (copyOver && donghuaOver && updateOver) {
//					jumpToBphsLoginActivityWithoutFinishSelf();
					to(BphsLoginActivity.class);
				}
				break;
			case COPY_FAILED:
				Toast.makeText(getApplicationContext(), "拷贝字数据库失败", Toast.LENGTH_SHORT).show();
				if (donghuaOver && updateOver) {
//					jumpToBphsLoginActivityWithoutFinishSelf();
					to(BphsLoginActivity.class);
				}
				break;
			case Constant.UPDATE_DOWNLOAD_CANCELED:
				dismissrogressBar();
				// if(donghuaOver){
//				jumpToBphsLoginActivityWithoutFinishSelf();
				to(BphsLoginActivity.class);
				break;
			case Constant.UPDATE_DOWNLOAD_ERROR:
				dismissrogressBar();
				Toast.makeText(getApplicationContext(), "更新数据库失败！", Toast.LENGTH_SHORT).show();
				// if(donghuaOver){
//				jumpToBphsLoginActivityWithoutFinishSelf();
				to(BphsLoginActivity.class);
				break;
			case Constant.UPDATE_DOWNLOADING:
				splash_progressbar.setVisibility(View.GONE);
				// loadWaitPanel("正在更新字典数据库，请稍候......");
				loadWaitPanelNoAutoClose("正在更新字典数据库，请稍候......", false);
				mIntent = new Intent(ctx, UpdataService.class);
				startService(mIntent);
				break;
			}
		};
	};

	private void jumpToBphsLoginActivityWithoutFinishSelf(){
		toNoFinish(BphsLoginActivity.class);
	}

}